<template>
  <div class="login-container">
    <!-- 存放后台加载数据 -->
    <!-- <div class="login-left">
            <p class="login-left-title">SnnGrow生长</p>
            <p>世界首个因果学习框架</p>
            <p class="login-left-title">世界先进类脑人工智能技术研发商</p>
            <p>让机器像人一样拥有智慧</p>
            <p class="login-left-title">UtarnGs类脑电竞AI</p>
            <p>像人一样的打电竞</p>
            <p class="login-left-title">VxBrain思辩</p>
            <p>新一代超级类脑计算机</p>
        </div> -->
    <div class="login-right">
      <div class="main">
        <img
          src="https://fuss10.elemecdn.com/3/28/bbf893f792f03a54408b3b7a7ebf0jpeg.jpeg"
          class="log"
        />
        <h3>让科研不在"孤岛" · MAKE MACHINE WISE</h3>
        <div class="section">
          <span>还没有UTARN账号?</span>
          <a @click="turnRegister">立即注册 </a>
        </div>
      </div>
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="formRules"
        validate-on-rule-change
      >
        <el-form-item prop="userTel">
          <el-input
            v-model="loginForm.userTel"
            placeholder="邮箱/手机号"
            @blur="validateHandler('userTel')"
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            autocomplete="off"
            placeholder="验证码"
            style="width: 250px"
            @blur="validateHandler('code')"
          />
          <el-button type="primary" :disabled="isDisabled" class="sendCode">
            <span v-if="isCodeShow" @click="sendEmailCode()">获取验证码</span>
            <span v-else>{{ count }} 秒后重新获取</span>
          </el-button>
        </el-form-item>
        <!-- <el-form-item prop="cote">
          <el-input
            v-model="loginForm.cote"
            placeholder="密码"
            show-password
            @blur="validateHandler('cote')"
          />
        </el-form-item> -->
        <div>
          <!-- <el-form-item prop="imgCode">
                        <el-input class="verify" v-model="loginForm.imgCode" placeholder="图片验证码" style="width:180px;" @blur="validateHandler('imgCode')"/>
                        <img :src="imgCode" @click="codeRefresh()" id="code"  title="点击刷新"> 
                    </el-form-item> -->
          <el-button
            class="login-btn"
            type="primary"
            :loading="loginLoading"
            @click="onLogin"
            >登录</el-button
          >
        </div>

        <div class="forget">
          <a @click="sms">手机号登录</a>
          <a @click="turnRetrieve">忘记密码？</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // imgCode:'/api/account/code/get',
      isCodeShow: true,
      existUsernameFlag: 0,
      count: 0,
      timer: {},
      loginForm: {
        userTel: "",
        cote: "",

        //imgCode:'',
      },
      loginLoading: false,
      formRules: {
        //表单验证用户：
        userTel: [
          { required: true, message: "账号不能为空", trigger: "change" },
          { validator: this.validateUsername, trigger: "change" },
        ],
        // //表单校验密码：
        cote: [
          { required: true, message: "密码不能为空", trigger: "blur,change" },
          // {min:6,max:16,message: '密码长度为6-16个字符', trigger: 'blur,change'},
        ],
        // imgCode:[{required: true, message:'图片验证码不能为空', trigger:'blur,change'}],
      },
    };
  },
  created() {
    this.searchEnter(this.onLogin);
  },
  watch() {
    this.validateUsername();
  },
  methods: {
    codeRefresh() {
      var codeImg = document.getElementById("code");
      codeImg.src = codeImg.src + "?" + Math.random();
    },

    sendEmailCode() {
      let TIME_COUNT = 60;
      if (Object.keys(this.timer).length == 0) {
        this.count = TIME_COUNT;
        this.isCodeShow = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.isCodeShow = true;
            clearInterval(this.timer);
            this.timer = {};
          }
        }, 1000);
      }
      console.log(this.loginForm.userTel);
      //var params = {account:this.resgisterForm.username}
      this.$axios(
        "https://localhost:44396/api/Service/login?args=" +
          this.loginForm.userTel
      )
        .then((res) => {
          this.$message.success("验证码已发送");
        })
        .catch((err) => {
          this.$message.error("发送失败");
        });
    },

    validateHandler(fieldName) {
      this.$refs.loginForm.validateField(fieldName);
    },

    searchEnter(func) {
      // 回车搜索
      document.onkeydown = (e) => {
        if (window.event == undefined) {
          var key = e.keyCode;
        } else {
          var key = window.event.keyCode;
        }
        //enter的ASCII码是13
        if (key == 13) {
          func();
          document.onkeydown = null;
        }
      };
    },
    onLogin() {
      this.createOrUpdate("https://localhost:44396/api/account/user/login");
    },
    createOrUpdate(url) {
      let valid;
      this.$refs.loginForm.validate((v) => (valid = v));
      if (!valid) {
        return;
      } //验证不通过
      //   let params = this.loginForm;
      this.$axios
        .get(url, {
          params: {
            UserTel: this.loginForm.userTel,
            code: this.loginForm.code,
          },
        })
        .then((res) => {
          console.log(res.data);
          if (res.data.result == "登录失败！") {
            this.$message.error("登录失败");
            return;
          } else {
            this.$message.success("登录成功");
            localStorage.setItem("userinfo", res.data.result.Id);
            this.$router.push("Order");
            // this.sms(res);

            console.log(this.successHandler);
          }
        })
        .catch(this.failHandler);
    },
    validateUsername(rule, value, callback) {
      let patternMail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      let patternMobile = /^[1][3,4,5,6.7,8,9][0-9]{9}$/;
      if (value.match(patternMail) || value.match(patternMobile)) {
        callback();
      } else {
        callback(new Error("邮箱/手机号"));
      }
    },
    getQueryParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
    turnRegister() {
      this.$router.push("Registered");
    },
    turnRetrieve() {
      let returnUrl = this.getQueryParam("returnUrl") || "";
      this.$router.push({
        path: "/passport/retrievepwd",
        query: { returnUrl: returnUrl },
      });
    },
    sms(res) {
      // alert(res.data.result.Id);
      // window.Storage.setItem("user", res.data.result.Id);
      //   this.$router.push("Order");
    },
    /*公共方法 */
    failHandler(err) {
      let response = err.response;
      if (!response) {
        this.$message.error(err.message);
        return;
      }
      let errMsg = err.response.data.msg || "操作失败了！";
      this.$message.error(errMsg);
      this.codeRefresh();
    },
    successHandler(res) {
      let userinfo = JSON.stringify(res.data.data);
      window.localStorage.setItem("userinfo", userinfo);
      let returnUrl = this.getQueryParam("returnUrl");
      if (returnUrl) {
        self.location = returnUrl;
      } else {
        self.location = "https://www.utarn.com";
      }
    },
  },
};
</script>

<style scoped>
.main .log {
  width: 186px;
  height: 68px;
  margin-top: 20px;
  margin-left: 63px;
}
.main h3 {
  color: #a93ac2;
  font-size: 15px;
  text-align: center;
}
.section span {
  color: rgba(61, 46, 46, 0.699);
  margin-left: 57px;
  font-size: 15px;
}
.section {
  margin-bottom: 15px;
}
.section a {
  margin-left: 20px;
  margin-right: 0px;
  color: #a93ac2;
  text-decoration: none;
}
.input-content {
  width: 100%;
  height: 120px;
}
.login-container {
  z-index: -999;
  margin: 150px auto;
  width: 400px;
  /* width:1200px; */
  height: 450px;
}
.login-left,
.login-right {
  padding: 10px 30px;
  height: 450px;
  float: left;
}
.login-left {
  text-align: center;
  width: 450px;
}
.login-right {
  width: 370px;
  border: 1px solid #a0b1c4;
  border-radius: 5px;
}
.login-left-title {
  font-size: 24px;
  font-weight: 600;
  color: #a994de;
}
.title {
  font-size: 26px;
  line-height: 50px;
  font-weight: bold;
  margin: 10px;
  text-align: center;
}
.login-btn {
  background-color: #a93ac2;
  border: 1px solid #a93ac2;
  width: 100%;
}
#code {
  width: 140px;
  height: 40px;
  margin-left: 47px;
  padding-left: 0px;
  vertical-align: middle;
  border-radius: 3px;
}
#code:hover {
  cursor: pointer;
}
.forget a {
  font-size: 15px;
  color: #676767;
  text-decoration: none;
  float: right;
  padding-top: 15px;
}
a {
  cursor: pointer;
}
</style>